package com.itheima.pinda.init;

import com.itheima.pinda.entity.ScheduleJobEntity;
import com.itheima.pinda.mapper.ScheduleJobMapper;
import com.itheima.pinda.utils.ScheduleUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 在项目启动时初始化定时任务
 *
 * @author llhuang10
 * @date 2021/10/25 10:10
 */
@Slf4j
@Component
public class DispatchCommandLineRunner implements CommandLineRunner {

    @Resource
    private Scheduler scheduler;

    @Resource
    private ScheduleJobMapper scheduleJobMapper;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始进行定时任务初始化...");

        // 1.查询定时任务表 schedule_job 中所有的数据
        List<ScheduleJobEntity> scheduleJobList = scheduleJobMapper.selectList(null);

        scheduleJobList.forEach(job -> {
            // 获取触发器对象
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, job.getId());
            if (cronTrigger == null) {
                // 触发器对象为空, 说明对应的定时任务没有创建
                ScheduleUtils.createScheduleJob(scheduler, job);
            } else {
                // 触发器对象不为空, 说明对应的定时任务已经存在了, 此时只需要更新
                ScheduleUtils.updateScheduleJob(scheduler, job);
            }
        });
    }
}
